from my_crawer import url_manager, html_parser, html_downloader, data_saver


class Spider_main(object):

    def __init__(self):
        self.urls = url_manager.UrlManager()
        self.parser = html_parser.HtmlParser()
        self.downloader = html_downloader.HtmlDownloader()
        self.data = data_saver.DataSaver()

    def craw(self, root_utl):
        # 计数器,起止条件控制
        count = 1
        # 目标url
        self.urls.add_new_url(root_utl)
        # 判断是否有带爬取的url,有的话则循环继续;
        while self.urls.has_new_url():
            try:
                # 获取待爬取的新url
                new_url = self.urls.get_new_url();
                print(count, new_url)
                # 获取到新的url 之后,下载新的url
                html_content = self.downloader.download(new_url)
                # 将新的url和下载的内容传递给 网页分析器 html_parser,分析器返回新的url和data

                new_urls, new_data = self.parser.parse(new_url, html_content)
                self.urls.add_new_urls(new_urls)
                self.data.save_data(new_data)

                # 满足条件,则循环终止
                if count == 10000:
                    break
                count = count + 1

            except BaseException as e:
                print('爬取失败',e)


if __name__ == '__main__':
    root_url = 'https://baike.baidu.com/item/CSS/5457'
    obj_spider = Spider_main()
    obj_spider.craw(root_url)
